<?php
/* 20101218: Captcha supported
 * 20110510: Support forget_password / reset_password
 * 201111  : change base path to /cms/builder/
 * 20120229: change to suppport mobile
 */


require_once(dirname(dirname(dirname(__FILE__))).'/appconf.php');
require_once 'CMS.class.php';

$local_config = array(
    'this_cgi'       => 'cms/builder/login.php',
    'tmpl'           => array('base_path' => 'cms/builder/login/'), # for load_action_tmpl
    'pass_hash_key'	 => 'g506fJcpjekBveixezRFrpcNyALmO0f3XEtuJgP4_Ut-',
    'database'       => '',
    'table'          => '',
);

class app_cms_login extends CMS{

  function setup(){
    $this->run_modes('login', 'logout',
                     'showlogin', 'edit', 'update', 
                     'show_forget_password', 'forget_password', 'verify_forget_password',
                     'new_password'
                    );
    $this->start_mode('showlogin');    
    parent::setup();
  }

	function cgiapp_prerun($rm=''){	
		#echo "no cgiapp_prerun()";
    #$this->prerun_mode('showlogin');
    #return ;
	}
	
	# for showing message dialog
  function cgiapp_postrun(&$body){
    parent::cgiapp_postrun($body);

      
    if ($this->header_type() == 'redirect'){
      return;	
    }
    
    $a_js = array();
    
    $a_msg = array();
    $a_current_msg = $this->message();
    $a_session_msg = $this->get_message_from_session();
    foreach ($a_session_msg as $msg){
    	array_push($a_msg, $msg);
    }
    foreach ($a_current_msg as $msg){
    	array_push($a_msg, $msg);
    }
    
    $message = '';
    if (count($a_msg)>0){
      $message = implode('<BR>', $a_msg);
      array_push($a_js, "\$(document).ready(function(){ $(\"#dialog-modal\").dialog({height: 140,modal: true});  });");
    }

    if (count($a_js) > 0){
      $temp = "<script>".implode('', $a_js)."</script>";
      if ($message != ''){
        $temp .= html_dialog('Notice', $message);
      }
      $body = preg_replace('/(<!--POSTRUNJS-->)/', $temp, $body, 1);
      
    }
    
  }	
	
	
	function get_landing_url(){
		$landing = $this->get_q('_done');
    if ($landing == ''){
    	$landing = isset($_SERVER['HTTP_REFERER'])? $_SERVER['HTTP_REFERER']: $this->param('INDEX');
    }
    return $landing;
	}
	
##########################################################################
# action show_login & login : for general login
##########################################################################
	
	function showlogin($status=''){
		
    $landing = $this->get_landing_url();
    $this->param('landing', $landing);
   
    $login = $this->get_q('login');
    if ($this->get_q('debug') != '' && $login != ''){
      $this->message($this->get_login_debug($login)); 
    }
 
	  return parent::showlogin($status);
	}
	
	function action_login(){
		
		# when access '.done', need o use '_done' instead, 
		$landing = $this->get_q('_done', $_SERVER['HTTP_REFERER']);	   
	  $this->param('_done', $landing);
	  
	  return parent::login();
	}
	
	# to be replace cms/logout.php, but all cms need to be published
  function action_logout(){
  	$this->s_param("~CMS_logged-in", 0);
	  
	  require_once('CMS_LoginCookie.class.php');
	  $login_cookie = new CMS_LoginCookie();
    $login_cookie->clear();
    
  	if (file_exists($this->param('WWW').'cms/builder/index.php')) {
      return $this->redirect('/cms/builder/index.php');
    } 
  	return $this->redirect('/');
  }	

##########################################################################
# action edit & update : for change password
##########################################################################

	# show update password page
	function action_edit(){
    $landing = $this->get_landing_url();
    $this->tmpl_assign('done',  $landing);
    $this->tmpl_assign('login', $this->get_q('login'));
    $this->tmpl_assign('cms_name', $this->cms_site_name());
     
    return $this->load_action_tmpl('edit');
	}

  # update user password
  function action_update(){
  	if ($this->verify_captcha() == 0){ 
      return $this->cms_login_redirect_to('edit', '驗証碼錯誤。');
    }
      	
  	$landing = $this->get_q('_done', $_SERVER['HTTP_REFERER']);	   
	  $this->param('_done', $landing);

	  return parent::update_password();  	
  }	

  function cms_login_redirect_to($action, $error_msg){
  	$h_param = array('action'=>$action);
  	$login   = $this->get_q('login');
  	$landing = $this->get_q('_done');
    if (!empty_string($login)){
    	$h_param['login'] = $login;
    } 
    if (!empty_string($landing)){
    	$h_param['.done'] = $landing;
    } 
    $this->message($error_msg);
    return $this->cms_redirect_default_action($h_param, 'querystr');
  }

##########################################################################
# action show_forget_password & forget_password : for retrieve password
##########################################################################

  function action_show_forget_password(){
  	$login = $this->get_q('login');
  	$landing = $this->get_landing_url();
    
  	$email = $this->get_cms_user_email($login);
  	if ($login != '' && $email == ''){
  		return $this->cms_login_redirect_to('showlogin', '用戶並未有登記電郵，請聯絡管理員重設密碼。');
    }
    
    $this->tmpl_assign('done',  $landing);
    $this->tmpl_assign('login', $this->get_q('login'));
    $this->tmpl_assign('cms_name', $this->cms_site_name());
        
  	return $this->load_action_tmpl('show_forget_password');    
  }
  
  
  
  function action_forget_password(){
    if ($this->verify_captcha() == 0){ 
      return $this->cms_login_redirect_to('show_forget_password', '驗証碼錯誤。');
    }
    
  	$login = $this->get_q('login');

  	$email = $this->get_cms_user_email($login);
  	if ($email != ''){
  	  #$this->message("Forget password email for user $login will be send to : $email.");
  	  
      $url = $this->get_reset_password_url($login);
  	  $body = 'Please goto: '. $url .' to reset your password';
  	  $h_data = array('subject' => 'Update CMS password',
  	                  'from_email' => 'online-no-reply@nmg.com.hk',
  	                  'to_email'   => $email,
  	                  'body'       => $body,
  	                  );
  	  $this->send_mail($h_data); 
  	  # 
  	  #return $this->redirect($url);   
  	  $message = '重設密碼電郵已發送到 '.$email.'，請根據電郵步驟重設密碼。';  
  	  
  	} else {
  		$message = '用戶並未有登記電郵，請聯絡管理員重設密碼。';
  	}

  	return $this->cms_login_redirect_to('showlogin', $message);
  }
  
  function action_verify_forget_password(){
  	$login = $this->get_q('login');
  	$code = $this->get_q('code');
  	
		$valid = $this->verify_reset_password_code($login, $code);
			
		if ($valid == 0){
			$this->message('login:'.$login);
			$this->message('Code:'.$code);
			$this->message('Failed to verify reset passowrd code.');
			return  $this->cms_redirect_default_action( array() );    
		}
		
    $this->tmpl_assign('login', $this->get_q('login'));
    $this->tmpl_assign('cms_name', $this->cms_site_name());
    $this->tmpl_assign('code',  $code);
		#$this->message('user can access email box of '.$login);
  	return $this->load_action_tmpl('show_new_password');
  }
  
  # set new password
  function new_password(){
    $login = $this->get_q('login');
  	$code = $this->get_q('code');
  	$new_password1 = $this->get_q('new_password1');
  	$new_password2 = $this->get_q('new_password2');
		$valid = $this->verify_reset_password_code($login, $code);
			
		if ($valid == 1 && $new_password1 == $new_password2){
	    $this->update_cms_password($login, $new_password1);	  
			#return $this->info("用戶 $login 密碼已重設。"); 
			$message = "用戶 $login 密碼已重設。";
			$this->q_param('_done', '/cms/builder/index.php');
			return $this->cms_login_redirect_to('showlogin', $message);
	  }
	  
	  if ($new_password1 != $new_password2){
	  	return $this->info("請輸入相同密碼。"); # code is not carried in page, need user to press 'back' in browser 
	  }
	
		#return $this->info("密碼重設連結已經失效，".html_link('請重試', '/cms/login.php/show_forget_password')."。"); 
		$message = '密碼重設連結已經失效，請重試。';
		return $this->cms_login_redirect_to('action_show_forget_password', $message);
  }
  
  function info($message){
  	$this->tmpl_assign('message', $message);
  	$this->tmpl_assign('cms_name', $this->cms_site_name());
    return $this->load_action_tmpl('info');
  }

	function send_mail($h_data){  
	  # start of header.
	  $subject = "=?UTF-8?B?". base64_encode($h_data['subject']). "?=";
	  $a_header = array();
	  
	  array_push($a_header, "MIME-Version: 1.0");
	  array_push($a_header, "Content-type: text/plain; charset=utf-8");
	  
	  if ($h_data['from_name'] == ''){
	    array_push($a_header, "From: ".$h_data['from_email']);
	  } else {
	    array_push($a_header, "From: \"". $h_data['from_name']. "\" <". $h_data['from_email']. "> ");
	  }
	  
	  # end of header.
	  # add and extra line:
	  $header = implode("\r\n", $a_header);
	  $header .= "\r\n";
	  
	  @mail($h_data['to_email'], $subject, $h_data['body'], $header);
	  return true;
	 }
	 


}//end class

$webapp = new app_cms_login(
   array('PARAMS' => array_merge($site_global_config, $local_config))
         );
$webapp->run();

?>
